var formfield, tbframe_interval;

jQuery(document).ready(function($) {
	$('.upload_header_image').live('click', function() {
		formfield = '#header_image_url';
		tb_show('', 'media-upload.php?post_id=0&#038;type=image&#038;TB_iframe=1');
		
		tbframe_interval = setInterval(function() {
			$('#TB_iframeContent').contents().find('.savesend .button').val('Use This Image');
		}, 2000 );
		
		return false;
	});
	
	$('#header_image_url').live('focus', function() {
		$('.upload_header_image').trigger('click');
	});
	
	$('.preview .delete_header_image').live('click', function() {
		removeImage();
	});
	
	// Get original send to editor because we are about to override it
	window.original_send_to_editor = window.send_to_editor;
	
	// Custom function to override where media upload sends data
	window.send_to_editor = function(html) {
		if ( formfield == '#header_image_url' )
		{
			var imgid = 0;
			var imgclass = $('img', '<p>' + html + '</p>').attr('class');
			if ( imgclass.indexOf( 'wp-image-') > -1 )
			{
				imgid = imgclass.slice( imgclass.indexOf( 'wp-image-') + 9  );
			}
			var imgurl = $('img', '<p>' + html + '</p>').attr('src');
			tb_remove();
			renderImage(imgid, imgurl );
			formfield = '';
			clearInterval(tbframe_interval);
		}
		else
		{
			window.original_send_to_editor(html);
		}
	}
});

function renderImage(imgid, img)
{
	jQuery('.header_image_container').html('<label>Image</label><input type="text" value="' + img + '" id="header_image_url" name="'+um_image_header_field+'" /><input type="hidden" name="'+um_image_id_field+'" value="'+imgid+'" />');
	
	jQuery('.preview').html('<a class="delete_header_image" href="javascript:void(0);">Remove Image</a>' +
		'<p class="header-preview-image">' + 
			'<img src="' + img + '" alt="" />' + 
		'</p>'
	);
	
	jQuery('.header-preview-image .delete_header_image').click(function() {
		removeImage();
	});
}

function removeImage()
{
	jQuery('.preview').html('');
	
	jQuery('.header_image_container').html('<label>Image</label><input type="text" value="" id="header_image_url" name="'+um_image_header_field+'" />');
}